﻿using System;
using System.Web;
using Domino;
using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.InteropServices;


namespace NotesCommonProjects
{
    public class NotesCF
    {
        public NotesCF()
        {
        }

        //靜態字串相關參數
        public static string TNotes01 = "TNOTES01/T/CCP";
        public static string KNotes01 = "KNOTES01/K/CCP";
        public static string ReferenceDatabase = "Refe0.NSF";           //參考資料庫(TNOTES01)
        public static string StationeryDatabase = "Stationery.NSF";     //總務用品申請(TNOTES01)
        public static string InOutDatabase = "INOUT.NSF";               //出勤刷卡系統(TNOTES01)
        public static string SapprovalDatabase = "SAPPROVAL.NSF";       //初代簽核流程(TNOTES01)
        public static string KnewProjectDatabase = "knewProject.nsf";   //承攬商入廠申請網路申報系統(KNOTES01)

        public static string SampleDocumnetRequester = "周正欣";   //範本文件申請人
        public static string SampleDocumentPpscode = "29137";
        public static string MyIdPassword = "kizuki33";            //我的ID檔密碼
        public static string AutoCCPTIdPassword = "TnCaY6DHUsf8";  //AutoCCPT ID檔密碼
        public static string ExceptionXMLHeader = "<Exception><Type>Exception</Type><Message>";
        public static string ExceptionXMLTail = "</Message></Exception>";

        //iSender相關參數
        public static string PostURL = "http://ios.ccp.com.tw/Chris/ccpsip/Message/robot_send_text.ashx";
        public static string RobotStationeryServiceID = "NotesStationery";
        public static string RobotStationeryServicePassword = "XaX6amDmScZGP7vKwj4R";

        //機器人訊息相關參數
        public static string SuccessMessage(string t_name, string t_spec)
        {
            return "您的【" + t_name + "," + t_spec + "】已申請成功並送簽；"
                + "若欲在手機上撤銷已申請過的總務用品，只能撤銷【當天在手機上申請的總務用品】"
                + "與【簽核中】的申請，其餘情況請使用Notes系統撤銷申請單，謝謝您的使用。";
        }
        public static string FailedMessage = "申請失敗，請按照順序點選圖片！";
        public static string FailedMessage2 = "申請失敗，查不到您的員工編號，請聯絡負責人周正欣，台北分機【238】。";
        public static string ErrorMessage = "發生錯誤，請聯絡負責人周正欣，台北分機【238】。";
        public static string DeleteLastRequestSuccessMessage = "撤銷成功！";
        public static string DeleteLastRequestFailedMessage = "找不到上一筆要撤銷的申請單，無法撤銷！";
        public static string DeleteLastRequestFailedMessage2 = "您的申請單已簽核完畢，無法撤銷！";
        public static string DeleteLastRequestFailedMessage3 = "找不到上一筆要撤銷的申請單，無法撤銷！(您只能撤銷當日的申請單)";

        //Log相關參數
        public static string StationeryLogDir = "C:\\NotesAPILog\\Stationery\\";
        public static string AddAccessDocumentsLogDir = "C:\\NotesAPILog\\AddAccessDocuments\\";
        public static string CallComputerAssetNotesAgentLogDir = "C:\\NotesAPILog\\CallComputerAssetNotesAgent\\";
        public static string SendMailAgentLogDir = "C:\\NotesAPILog\\SendMailAgent\\";
        public static string CheckFactoryEntryApplyLogDir = "C:\\NotesAPILog\\CheckFactoryEntryApply\\";

        //錯誤訊息相關參數
        public static string ExceptionMessage_01 = "Error_01: Parameter error.";
        public static string ExceptionMessage_02 = "Error_02: PPS_CODE doesn't exist.";
        public static string ExceptionMessage_03 = "Error_03: iBeacon num error. Multiple ibeacon location is detected.";
        public static string ExceptionMessage_04 = "Error_04: Save Notes Document failed.";
        public static string ExceptionMessage_05 = "Error_05: Json object format error. ";

        //共用函式
        /// <summary>寫入Log</summary>
        /// <param name="log_dir">Log資料夾</param>
        /// <param name="context">Log內容</param>
        public static void WriteLog(string log_dir, string context)
        {
            //【01】檢查Log根目錄
            DirectoryInfo di = new DirectoryInfo(log_dir);
            if (!di.Exists)
                di.Create();

            //【02】檢查Log檔案
            string FileName = DateTime.Now.ToString("yyyy_MM_dd") + ".txt";

            //【03】將context寫入檔案
            FileStream fs = new FileStream(log_dir + FileName, FileMode.Append, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs);
            sw.Write(DateTime.Now.ToString("HH:mm:ss") + " : " + context + "\r\n\r\n");

            //【04】釋放資源
            sw.Dispose();
            fs.Dispose();
        }

        /// <summary>檢查Log檔案</summary>
        /// <param name="log_dir">Log目錄</param>
        /// <param name="file_name">Log檔案名稱</param>
        /// <returns>Log檔案是否存在</returns>
        public static bool CheckLogFile(string log_dir, string file_name)
        {
            //【01】檢查Log根目錄
            DirectoryInfo di = new DirectoryInfo(log_dir);
            if (!di.Exists)
                return false;

            //【02】檢查Log檔案
            FileInfo fi = new FileInfo(log_dir + file_name);
            if (!fi.Exists)
                return false;

            return true;
        }

        /// <summary>序列化物件</summary>
        /// <param name="input">物件</param>
        /// <returns>物件Json字串</returns>
        public static string Serialize(object input)
        {
            JavaScriptSerializer JsonSerializer = new JavaScriptSerializer();
            return JsonSerializer.Serialize(input);
        }

        /// <summary>將Exception轉成XML格式的字串</summary>
        /// <param name="ex">要轉換的Exception物件</param>
        /// <param name="includeStackTrace">要不要包含StackTrace</param>
        /// <returns>Exception詳細資訊(XML格式字串)</returns>
        public static string Ex2Xml(Exception ex, bool includeStackTrace)
        {
            string result = "<Exception>"
              + Environment.NewLine + "<Type>" + ex.GetType().Name + "</Type>"
              + Environment.NewLine + "<Message>" + ex.Message + "</Message>";

            if (includeStackTrace)
            {
                result += Environment.NewLine + "<StackTrace>";
                result += HttpUtility.HtmlEncode(ex.StackTrace) + "</StackTrace>";
            }
            result += Environment.NewLine + "</Exception>";
            return result;
        }

        /// <summary>釋放COM物件, 多載NotesSession</summary>
        /// <param name="session">NotesSession</param>
        public static void ReleaseComObject(ref NotesSession session)
        {
            if (session != null)    //檢查物件原本是否為空, 不然直接釋放會跳Exception
            {
                Marshal.ReleaseComObject(session);
                session = null;
            }
        }

        /// <summary>釋放COM物件, 多載NotesDatabase</summary>
        /// <param name="db">NotesDatabase</param>
        public static void ReleaseComObject(ref NotesDatabase db)
        {
            if (db != null)
            {
                Marshal.FinalReleaseComObject(db);
                db = null;
            }
        }

        /// <summary>釋放COM物件, 多載NotesView</summary>
        /// <param name="view">NotesView</param>
        public static void ReleaseComObject(ref NotesView view)
        {
            if (view != null)
            {
                Marshal.ReleaseComObject(view);
                view = null;
            }
        }

        /// <summary>釋放COM物件, 多載NotesDocument</summary>
        /// <param name="doc">NotesDocument</param>
        public static void ReleaseComObject(ref NotesDocument doc)
        {
            if (doc != null)
            {
                Marshal.ReleaseComObject(doc);
                doc = null;
            }
        }
    }
}